package org.com.f4.model;

import java.sql.ResultSet;
import java.sql.Statement;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

public class MyBatisPaginate {
	private SqlSessionFactory sqlSessionFactory;
	public static int getInt(Object o) {
		if (o instanceof Integer) {
			return (Integer) o;
		}
		if (o instanceof String) {
			return Integer.parseInt((String) o);
		}
		return 0;
	}

	public static String getString(Object o) {
		if (o instanceof Integer) {
			return Integer.toString((Integer) o);
		}
		if (o instanceof String) {
			return (String) o;
		}
		return "";
	}

	public MyBatisPaginate(SqlSessionFactory sqlSessionFactory) {
		this.sqlSessionFactory = sqlSessionFactory;
		sqlSessionFactory.getConfiguration().addMapper(MySQLFunction.class);
	}






	
	
	
	public Page execQueryPage(String sqlid,Page page1) {
		SqlSession session = null;
		try {
			session = sqlSessionFactory.openSession();
			//int start=(page1.getPageNum()-1)*page1.getPageSize();
			//获取查询的参数
			Map<String,Object> nparam=page1.getParams();
			//获取查询的数据
			List rowsData = session.selectList(sqlid, nparam, new RowBounds(page1.getPageNum(), page1.getPageSize()));
			//总条数
			int count = getFoundRows(session);
			page1.setList(rowsData);
			page1.setTotal(count);
			return page1;
		} finally {
			session.close();
		}
	}
	
	private int getFoundRows(SqlSession session) {
		int r = 0;
		try {
			Statement sm1;
			sm1 = session.getConnection().createStatement();
			ResultSet rs1 = sm1.executeQuery("select FOUND_ROWS() total");
			if (rs1.next()) {
				r = rs1.getInt(1);
			}
			sm1.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	return r;
}}



